const net = require('net')
const MyTransform = require('./transform-my')

const server = net.createServer()

let overageBuffer = null
let ts = new MyTransform()

server.listen(1234, 'localhost')

server.on('listening', () => {
  console.info(`服务已经启动 http://localhost:1234`)
})

// 监听连接
server.on('connection', (socket) => {
  socket.on('data', (chunk) => {
    if (overageBuffer) {
      chunk = Buffer.concat([overageBuffer, chunk])
    }

    let packageLen = 0
    while ((packageLen = ts.getPackageLen(chunk))) {
      const packageContent = chunk.slice(0, packageLen)
      chunk = chunk.slice(packageLen)

      const ret = ts.decode(packageContent)
      console.info(ret)
      socket.write(ts.encode(ret.body, ret.serialNum))
    }
    overageBuffer = chunk
  })
})
